package xian.woniuxy.service.impl;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import xian.woniuxy.entity.Role;
import xian.woniuxy.entity.RoleExample;
import xian.woniuxy.mapper.RoleMapper;
import xian.woniuxy.mapper.custom.CustomRoleMapper;
import xian.woniuxy.service.RoleService;

import java.util.ArrayList;
import java.util.List;

/**
 * @author gao
 * @date 2023/07/03 15:31:29
 */
@Service
@Transactional
public class RoleServiceImpl implements RoleService {

    @Autowired
    private CustomRoleMapper roleMapper;

    @Override
    public int save(Role role) {
        return roleMapper.insertSelective(role);
    }

    @Override
    public int delete(Integer roleId) {
        return roleMapper.deleteByPrimaryKey(roleId);
    }

    @Override
    public int update(Role role) {
        return roleMapper.updateByPrimaryKeySelective(role);
    }

    @Override
    public Role findOne(Integer roleId) {
        return roleMapper.findOneWithPermissions(roleId);
    }

    @Override
    public List<Role> findAll() {
        return roleMapper.selectByExample(null);
    }

    @Override

    public int distributePermissions(Integer rid, List<Integer> permissionIds) {
        int rows = 0;
        rows += roleMapper.clearRolePermissions(rid);
        if (permissionIds.size() > 0) {
            rows += roleMapper.distributePermissions(rid, permissionIds);
        }
        return rows;
    }

    @Override
    public List<Role> findByUserId(Integer userId) {
        List<Integer> roleIds = roleMapper.findRoleIdsByUserId(userId);
        List<Role> roles = new ArrayList<>();
        for (Integer roleId : roleIds) {
            Role role = roleMapper.selectByPrimaryKey(roleId);
            roles.add(role);
        }
        return roles;
    }
}
